const SECOND_MENU_NAMES = [];
const tagsView = {
  state: {
    visitedViews: [],
    cachedViews: SECOND_MENU_NAMES
  },
  mutations: {
    ADD_VISITED_VIEWS: (state, view) => {
      if (state.visitedViews.some(v => v.fullPath === view.fullPath)) return
      const formatterTitle = (title) => {
        if (title.match(/管理$/)) {
          if (view.fullPath.includes('type=view')) {
            title = title.replace(/管理$/, '详情');
          } else if (view.fullPath.includes('type=update')) {
            title = title.replace(/管理$/, '变更');
          }
        }
        if (view.fullPath.includes('type=view') && !title.includes('详情')) {
          title = title += '详情'
        }
        return title;
      }
      state.visitedViews.push(Object.assign({}, view, {
        title: formatterTitle(view.meta.title) || 'no-name'
      }))
      if (!view.meta.noCache && !state.cachedViews.includes(view.name)) {
        state.cachedViews.push(view.name)
      }
    },
    DEL_VISITED_VIEWS: (state, view) => {
      for (const [i, v] of state.visitedViews.entries()) {
        if (v.fullPath === view.fullPath) {
          state.visitedViews.splice(i, 1)
          break
        }
      }
      for (const cacheName of state.cachedViews) {
        if (cacheName === view.name) {
          const sameNameViewLength = state.visitedViews.filter(item => {
            return item.name === cacheName;
          }).length;
          if (sameNameViewLength === 0) {
            const index = state.cachedViews.indexOf(cacheName)
            state.cachedViews.splice(index, 1)
          }
          break
        }
      }
    },
    DEL_OTHERS_VIEWS: (state, view) => {
      for (const [i, v] of state.visitedViews.entries()) {
        if (v.fullPath === view.fullPath) {
          state.visitedViews = state.visitedViews.slice(i, i + 1)
          break
        }
      }
      for (const i of state.cachedViews) {
        if (i === view.name) {
          const index = state.cachedViews.indexOf(i)
          state.cachedViews = [...SECOND_MENU_NAMES, state.cachedViews.slice(index, i + 1)]
          break
        }
      }
    },
    DEL_ALL_VIEWS: (state) => {
      state.visitedViews = []
      state.cachedViews = SECOND_MENU_NAMES
    }
  },
  actions: {
    addVisitedViews({ commit }, view) {
      commit('ADD_VISITED_VIEWS', view)
    },
    delVisitedViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit('DEL_VISITED_VIEWS', view)
        resolve([...state.visitedViews])
      })
    },
    delOthersViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit('DEL_OTHERS_VIEWS', view)
        resolve([...state.visitedViews])
      })
    },
    delAllViews({ commit, state }) {
      return new Promise((resolve) => {
        commit('DEL_ALL_VIEWS')
        resolve([...state.visitedViews])
      })
    }
  }
}

export default tagsView
